<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>买点书练习</title>
</head>

<body>
    <div id="app">
        <div>
            <p>请选择你要购买的书籍</p>
            <ul>
                <li v-for="(item, index) in arr" :key="index">
                    {{ item.name }}
                    <button @click="buy(item.name, item.price)">买书</button>
                </li>

            </ul>
            <table border="1" width="500" cellspacing="0">
                <tr>
                    <th>序号</th>
                    <th>书名</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>合计</th>
                </tr>
                <tr v-for="(item, index) in list" :key="item.id">
                    <th>{{ item.id }}</th>
                    <th>{{ item.name }}</th>
                    <th>{{ item.price }}</th>
                    <th>{{ item.count }}</th>
                    <th>{{ item.price * item.count }}</th>
                </tr>
            </table>
            <p>总价格为: {{ total }} </p>
        </div>
    </div>
    <script src="../vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                arr: [
                    {
                        name: "水浒传",
                        price: 107,
                        count: 0,
                    },
                    {
                        name: "西游记",
                        price: 192,
                        count: 0,
                    },
                    {
                        name: "三国演义",
                        price: 219,
                        count: 0,
                    },
                    {
                        name: "红楼梦",
                        price: 178,
                        count: 0,
                    },
                ],
                list: [{
                    id: 1,
                    name: "水浒传",
                    price: 107,
                    count: 1,
                }]
            },
            methods: {
                buy(name, price) {
                    let is = this.list.filter(item => item.name === name).length
                    if (!is) {
                        this.list.push({
                            id: this.list.length + 1,
                            name,
                            price,
                            count: 1,
                        })
                    } else {
                        this.list.filter(item => item.name === name)[0].count += 1
                    }

                }
            },
            computed: {
                total() {
                    return this.list.reduce((sum, item) => sum + item.price * item.count, 0)
                }
            }
        })
    </script>
</body>

</html>